import { mgop } from '@aligov/jssdk-mgop'
import axios from './axios'

import getParam from '@/utils/parsingUrl'

import global from '@/global'

const ticket = getParam('ticket', window.location.href)
const sessionTicket = sessionStorage.getItem('ticket')

interface ParamsType {
  localUrl: string
  onLineUrl: string
  [params: string]: any
}

// 是否是本地开发模式，发布前更改    true:是  false:否
// const isDev = true

export default {
  // get请求
  get(queryParams: ParamsType) {
    return new Promise((resolve, reject) => {
      if (global.isDev) {
        axios
          .get(queryParams.localUrl, { params: queryParams.params })
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      } else {
        mgop({
          api: queryParams.onLineUrl,
          host: 'https://mapi.zjzwfw.gov.cn/',
          header: {
            'Content-Type': 'multipart/form-data',
            ticket: ticket || sessionTicket
          },
          data: queryParams.params,
          appKey: '9c917epq+2002282000+nyfgdi', // 必 须
          onSuccess: (res: { data: unknown }) => {
            console.log(`get mgop success ${queryParams.localUrl} res：`, res)
            resolve(res.data)
          },
          onFail: (err: any) => {
            console.log(`get mgop err ${queryParams.localUrl} res：`, err)
          }
        })
      }
    })
  },
  // post请求
  post(queryParams: ParamsType) {
    return new Promise((resolve, reject) => {
      if (global.isDev) {
        axios
          .post(queryParams.localUrl, queryParams.params, queryParams.headers || {})
          .then((res) => {
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      } else {
        mgop({
          api: queryParams.onLineUrl, // 必须
          host: 'https://mapi.zjzwfw.gov.cn/',
          header: { ticket: ticket || sessionTicket },
          data: queryParams.params,
          appKey: '9c917epq+2002282000+nyfgdi', // 必 须
          onSuccess: (res: { data: unknown }) => {
            console.log(`post mgop success ${queryParams.onLineUrl} res：`, res)
            resolve(res.data)
          },
          onFail: (err: any) => {
            console.log(`post mgop err ${queryParams.onLineUrl} res：`, err)
          }
        })
      }
    })
  }
}
